﻿using Microsoft.Extensions.DependencyInjection;
using ZeroSum.Constants;
using ZeroSum.DataEncryption.Encryptions;
using ZeroSum.DependencyInjection.Attributes;
using ZeroSum.Domain.Repositories;
using ZeroSum.Exceptions;
using ZeroSum.Plugin.Authentication.JwtBearer.Authentication;
using ZeroSum.Plugin.Authorization.Datas.Dto.In;
using ZeroSum.Plugin.Authorization.Datas.Dto.Out;
using ZeroSumZSA.Core.Aggregates.UserAggregate;
using ZeroSumZSA.Core.DomainServices.Users;

namespace ZeroSumZSA.Application.ApplicationServices.Auths;

/// <summary>
///     登录授权相关服务
/// </summary>
[Register(ServiceLifetime.Scoped)]
public class AuthApplicationService : IAuthApplicationService
{
    private readonly IJwtBearerService _jwtBearerService;
    private readonly IUserDomainService _userDomainService;

    public AuthApplicationService(IJwtBearerService jwtBearerService, IUserDomainService userDomainService)
    {
        _jwtBearerService = jwtBearerService;
        _userDomainService = userDomainService;
    }

    public async Task<TokenDto?> LoginAsync(LoginDto loginDto)
    {
        var encryptPassword = MD5Encryption.Encrypt(loginDto.Password!);

        var query = QueryByEntity<User>.Of(query =>
            query.Where(x => x.Account == loginDto.Account && x.Password == encryptPassword));
        var user = await _userDomainService.FirstOrDefaultAsync(query);

        if (user == null)
            throw NoMatchedResultException.Of("该用户不存在！");

        var accessToken = _jwtBearerService.CreateToken(new Dictionary<string, object>
        {
            {ClaimConst.CLAINM_USERID, user.Id},
            {ClaimConst.TENANT_ID, ""},
            {ClaimConst.CLAINM_ACCOUNT, user.Account!},
            {ClaimConst.CLAINM_NAME, user.Name!},
            {ClaimConst.CLAINM_SUPERADMIN, ""}
        });

        var refreshToken = _jwtBearerService.GenerateRefreshToken(accessToken);

        return new TokenDto(accessToken) {RefreshToken = refreshToken};
    }
}